package com.yk.i_wms.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yk.i_wms.common.model.Result;
import com.yk.i_wms.dto.SmsBarcodeDTO;
import com.yk.i_wms.mapper.SmsBarcodeMapper;
import com.yk.i_wms.model.SmsBarcode;
import com.yk.i_wms.service.ISmsBarcodeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 
 *
 * @author hbq
 * @date 2021-04-02 13:29:50
 */
@Slf4j
@Service
public class SmsBarcodeServiceImpl extends ServiceImpl<SmsBarcodeMapper, SmsBarcode> implements ISmsBarcodeService {
    @Resource
    private SmsBarcodeMapper smsBarcodeMapper;
    /**
     * 列表
     * @param params
     * @return
     */
    public Page<Map> findList(Map<String, Object> params){
        Integer pageNum = MapUtils.getInteger(params, "pageNum");
        Integer pageSize = MapUtils.getInteger(params, "pageSize");
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = -1;
        }
        Page<Map> pages = new Page<>(pageNum, pageSize);
        return smsBarcodeMapper.findList(pages, params);
    }

    @Override
    public Result createBarCode(SmsBarcodeDTO smsBarcodeDTO) {
        List<SmsBarcode> smsBarcodes=new ArrayList<>();
        String itemCode = smsBarcodeDTO.getItemCode();          //物料代码
        Long itemMinPack = smsBarcodeDTO.getItemMinPack();      //最小包装数
        Long planNum = smsBarcodeDTO.getPlanNum();              //送货数量
        Integer num = smsBarcodeDTO.getNum();                   //生成数量
        String maxNo = getNewNo(itemCode);                      //当前最大条码
        if (itemMinPack<=0){
            return Result.failed("最小包装数错误");
        }
        Long totalNum=0L;
        for (Integer i = 1; i <= num; i++) {
            SmsBarcode smsBarcode = new SmsBarcode();
            //计算出新的sn
            String[] split = maxNo.split("\\|");
            String suffix = split[split.length - 1];
            String prefix = StrUtil.removeSuffix(maxNo, suffix);
            Long serialNumber = Convert.toLong(suffix)+i-1;
            String sn=prefix+String.format("%4d",serialNumber).replace(" ","0");
            smsBarcode.setSn(sn);
            //计算出新的数量
            if (i*itemMinPack<=planNum){
                smsBarcode.setSnNum(itemMinPack);
                totalNum=totalNum+itemMinPack;
            }else {
                smsBarcode.setSnNum((planNum-totalNum)<=0?0:planNum-totalNum);
                totalNum=totalNum+planNum%itemMinPack;
            }

            smsBarcode.setItemCode(itemCode);
            smsBarcode.setBatch(smsBarcodeDTO.getBatch());
            smsBarcode.setDocNo(smsBarcodeDTO.getDocNo());
            smsBarcode.setPoNo(smsBarcodeDTO.getPoNo());
            smsBarcode.setItemName(smsBarcodeDTO.getItemName());
            smsBarcode.setSnTime(new Date());
            smsBarcode.setSnState(0);
            smsBarcode.setPdate(smsBarcodeDTO.getPdate());
            smsBarcodes.add(smsBarcode);
        }
        return Result.succeed(smsBarcodes,"生成成功");
    }

    @Override
    public Result createSingleBarCode(Map<String, Object> params) {
        String sn = MapUtil.getStr(params, "sn");
        SmsBarcode barcodeInfo = getOne(new LambdaQueryWrapper<SmsBarcode>().eq(SmsBarcode::getSn, sn));
        if (barcodeInfo == null) {
            return Result.failed("生成失败，请至少先保存一次条码信息");
        }
        String[] split = sn.split("\\|");
        String suffix = split[split.length - 1];
        String prefix = StrUtil.removeSuffix(sn, suffix);
        SmsBarcode newBarcodeInfo = getOne(new QueryWrapper<SmsBarcode>()
                .last("where sn like '" + prefix + "%' order by sn desc limit 1"));
        String newSn="";
        if (newBarcodeInfo != null) {
            Long aLong = Convert.toLong(StrUtil.removePrefix(newBarcodeInfo.getSn(), prefix));
            newSn=prefix+String.format("%4d",aLong+1).replace(" ","0");
        }
        barcodeInfo.setId(null);
        barcodeInfo.setSn(newSn);
        barcodeInfo.setSnNum(0l);
        return Result.succeed(barcodeInfo,"查询成功");
    }

    /**
     * 通过物料号查找当天最大串号
     * @param itemCode 物料号
     * @return  当天最大串号
     */
    private String getNewNo(String itemCode){
        //生成新的串号
        String prefix=itemCode+"|"+DateUtil.format(new Date(), "yyyyMMdd")+"|";
        String maxNo=prefix+"0001";
        SmsBarcode one = getOne(new QueryWrapper<SmsBarcode>()
                .last("where sn like '" + prefix + "%' order by sn desc limit 1"));
        if (one != null) {
            Long aLong = Convert.toLong(StrUtil.removePrefix(one.getSn(), prefix));
            maxNo=prefix+String.format("%4d",aLong+1).replace(" ","0");
        }
        return maxNo;
    }
}
